# app.py
import os
import uuid
import asyncio
from flask import Flask, render_template, request, url_for
import edge_tts

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'EdgeTTS/static/audio'

# 确保音频目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

async def generate_speech(text, output_path):
    try:
        communicate = edge_tts.Communicate(text, "zh-CN-XiaoxiaoNeural")
        await communicate.save(output_path)
        return True
    except Exception as e:
        print(f"Error generating speech: {e}")
        return False

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        text = request.form.get('text', '')
        if not text.strip():
            return render_template('index.html', error="请输入有效文本")

        # 生成唯一文件名
        filename = f"{uuid.uuid4().hex}.wav"
        output_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        
        # 异步执行语音生成
        success = asyncio.run(generate_speech(text, output_path))
        
        if success and os.path.exists(output_path):
            audio_url = url_for('static', filename=f'audio/{filename}')
            return render_template('result.html', 
                                audio_url=audio_url,
                                original_text=text)
        
        return render_template('index.html', error="语音生成失败，请重试")
    
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
